var express = require('express');
var router = express.Router();
var userinfoController  = require("../controller/userinfoController");

//引入token
var jwt = require("jsonwebtoken");
//引入加密模块
const crypto = require("crypto");


router.get("/get",(req,res,next)=>{
  let {query} = req;
  res.send({
    code:1,
    msg:'获取用户成功',
    query
  })
  // userinfoController.query(req.query)
})

//处理提交注册
router.post("/regiest", async (req, res, next) => {
  let { username, userpwd,type } = req.body;
  //注册前判断是否有该用户
  let ck = await userinfoController.query({
    username
  })
  if (!ck.length) {
    let md5 = crypto.createHash("md5");
    userpwd = md5.update(userpwd).digest("hex");
    let result = await userinfoController.add({
      username,
      userpwd,
      type
    })
    res.send({
      code: 1,
      msg: "注册成功",
      result
    })
  } else {
    res.send({
      code: 0,
      msg: "该用户已经存在，请勿重复注册"
    })
  }
})


//处理登录
router.post("/login", async (req, res, next) => {

  let { username, userpwd } = req.body

  let md5 = crypto.createHash("md5");
    userpwd = md5.update(userpwd).digest("hex");
  let result = await userinfoController.query({
    username,
    userpwd
  })
  if (result.length) {
    var type = result[0].type
    //生成token
    var token = jwt.sign({ username, userpwd,type}, "login", {
      expiresIn: 60 * 60 * 1  // 1小时过期
    })
    var path = 'shops';
    if(result[0].type == 1){
      path = 'express'
    }else if(result[0].type == 2){
      path = 'customer'
    }else{
      path = 'shops'
    }
    //1:表示外卖员  2:买家  3：商家
    res.send({
      code: 1,
      msg: "登录成功",
      data:{
        token,
        path,
        username:result[0].username
      }
    })
  } else {
    res.send({
      code: 0,
      msg: "用户名或密码错误,请重新登录"
    })
  }
})


router.get("/getAll",async (req,res,next)=>{
  let data = await userinfoController.query()
  res.send({
    code:1,
    msg:'获取成功',
    data
  })
  
})

module.exports = router;
